﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class RoleController : BaseController
    {
        RoleBO roleBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RoleController));

        public ActionResult Index(RoleModel m = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                SetActiveMenu("/Role/Index");
                if (m == null) m = new RoleModel();                
               
                var model = search(m, pageIndex, currentId, false);
                ViewBag.lstApp = CommonData.getListApp();
                return View("~/Views/Role/Role.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }



        /// Hiển thị form thêm mới vai trò
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateRole(int? id)
        {
            try
            {
                RoleModel model = null;
                if (id != null && id > -1)
                {
                    roleBO = new RoleBO();
                    model = new RoleModel(roleBO.GetRoleById(id));
                }
                if (model == null)
                {
                    model = new RoleModel()
                    {
                        RoleId = -1,
                        RoleName = string.Empty,
                        RoleCode = string.Empty,
                        RoleDescription = string.Empty,
                        IsActive = 1
                    };
                }
                ViewBag.lstApp = CommonData.getListApp();
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Role/_RoleModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(RoleModel aModel = null, int pageIndex = 0, string sort = "RoleId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/Role/_RoleList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Thêm mới vai trò
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateRole(RoleModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    roleBO = new RoleBO();
                    bool result = roleBO.createOrUpdateRole(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<RoleModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateRole", model);

                        if (model.RoleId > -1)
                        {
                            return Json(JsonResponse.Json200("Cập nhật vai trò thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới vai trò thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] roleList)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    roleBO = new RoleBO();
                    bool result = roleBO.deleteRole(roleList);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(roleList),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa vai trò thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<RoleModel> search(RoleModel myModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                roleBO = new RoleBO();

                var DALModel = roleBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<RoleModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.RoleModel gender in lstItem)
                {
                    models.Data.Add(new RoleModel(gender));
                }

                RoleModel model = null;
                if (currentId >= 0 && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => user.RoleId == currentId);
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Role",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "role-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra tên vai trò đã tồn tại chưa
        public JsonResult CheckExistRoleName(string roleName, int? RoleId, int AppId)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(roleName))
                {
                    RoleModel roleModel = new RoleModel()
                    {
                        RoleName = roleName.Trim(),
                        AppId = AppId,
                        IsActive = 2
                    };
                    var model = search(roleModel, 0, -1, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (RoleModel role in lstItem)
                        {
                            if (RoleId != null && RoleId > 0)
                            {
                                if (role.RoleId != RoleId)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.RoleNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã vai trò đã tồn tại chưa
        public JsonResult CheckExistRoleCode(string roleCode, int? RoleId, int AppId)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(roleCode))
                {
                    RoleModel roleModel = new RoleModel()
                    {
                        RoleCode = roleCode,
                        AppId = AppId
                    };
                    var model = search(roleModel, 0, -1, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (RoleModel role in lstItem)
                        {
                            if (RoleId != null && RoleId > 0)
                            {
                                if (role.RoleId != RoleId)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.RoleCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckExistRoleNameView(string roleName, int? RoleId, int AppId)
        {
            try
            {
                RoleModel roleModel = new RoleModel()
                {
                    RoleName = roleName.Trim(),
                    AppId = AppId,
                    IsActive = 2
                };
                var model = search(roleModel, 0, -1, true);
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (RoleModel role in lstItem)
                    {
                        if (RoleId != null && RoleId > 0)
                        {
                            if (role.RoleId != RoleId)
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckExistRoleCodeView(string roleCode, int? RoleId, int AppId)
        {
            try
            {
                RoleModel roleModel = new RoleModel()
                {
                    RoleCode = roleCode,
                    AppId = AppId
                };
                var model = search(roleModel, 0, -1, true);
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (RoleModel role in lstItem)
                    {
                        if (RoleId != null && RoleId > 0)
                        {
                            if (role.RoleId != RoleId)
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListApp()
        {
            try
            {
                ApplicationBO appBO = new ApplicationBO();
                var lstType = appBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "0",
                    Text = "Chọn ứng dụng"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.AppId.ToString(),
                        Text = type.AppName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch
            {
                throw;
            }
        }

        private string GetFunction()
        {
            return "Quản trị vai trò - RoleController";
        }
    }
}